package com.glory.brepda.activity.mfg;

/**
 * 载具绑定批次
 */

import android.os.Handler;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.LotBindAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.MyUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;


public class LotBindActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etBingLotID)
    FreeUI_ClearEditText etBingLotID;
    @BindView(R.id.rvLotList)
    RecyclerView rvLotList;
    @BindView(R.id.etLotID)
    FreeUI_ClearEditText etLotID;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvStepName)
    TextView tvStepName;
    @BindView(R.id.tvMainqty)
    TextView tvMainqty;

    // 输入设备号
    FreeUI_ClearEditText etEquipmentId;

    // 绑定载具类别下拉选择框
    // fl(FrameLayout)、tv(TextView)、iv(ImageView)
    FrameLayout flCarrierType;
    TextView tvCarrierType;
    ImageView ivCarrierType;

    // 料盒类别下拉框配置
    private FreeUI_GeneralPop carrierTypePop;
    private final ArrayList<String> carrierBindTypeList = new ArrayList<>(Arrays.asList("料盒","黑箱"));

    // 输入料盒号验证是否和批次进行了绑定
    FreeUI_ClearEditText etVerifyBingLotID;

    RecyclerView rvAlreadyBindCarrierList;
    private LotBindAdapter mLotBindAdapter;
    private LotCarrierVerifyAdapter lotAlreadyBindAdapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_lotbind;
    }

    @Override
    protected void initView() {
        initLayout();

        initEdit(etBingLotID, s -> {

            if (StringUtils.isAnyEmpty(getText(etEquipmentId), getText(etLotID))){
                showConfirmDialog("请先扫描批次号和设备号，再绑定载具");
                return;
            }

            try {
                if (StringUtils.isEmpty(s)) {
                    return;
                }

                for (String entity : mLotBindAdapter.getData()) {
                    if (s.equals(entity)) {
                        showToast("当前载具已加载到列表中", false);
                        return;
                    }
                }

                // 检查扫入的料盒号是否已经在后台进行了绑定
                // （注：料盒列表是根据批次号和设备号来执行查询的，有可能回查不全但是执行绑定的时候会进行检验）
                lotAlreadyBindAdapter.setSearchQuery(s);
                if (lotAlreadyBindAdapter.isSearchSuccess()) {
                    showToast("当前载具已经和批次绑定", false);
                    return;
                }

                mLotBindAdapter.addData(s);
                etBingLotID.setText("");
            } finally {
                MyUtils.editTextRequestFocus(etBingLotID);
            }

        });

        initEdit(etLotID, s -> {
            //获取lot信息
            LotUtils.searchLotInfo(LotBindActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {
                    tvStepName.setText(response.getLOT().getSTEPNAME());
                    tvMainqty.setText(response.getLOT().getMAINQTY());
                    // 根据批次号、设备号执行查询载具列表
                    getLotBindCarrier();
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });
        });

        // 初始化扫描料盒号进行验证框 编辑事件，
        initEdit(etVerifyBingLotID, s -> {
            lotAlreadyBindAdapter.setSearchQuery(s);
            if (lotAlreadyBindAdapter.isSearchSuccess()) {
                showToast("成功匹配载具", true);
                // 匹配成功可清空掉输入框的信息，因成功匹配的字体颜色会变
                MyUtils.clearTextInTextView(etVerifyBingLotID);
                MyUtils.editTextRequestFocus(etVerifyBingLotID);
            } else {
                showToast("未匹配到载具", false);
            }
        });

        // 初始化设备号输入框编辑事件，触发查询料盒接口
        initEdit(etEquipmentId, s -> getLotBindCarrier());
    }

    private void initLayout() {

        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        initRecyclerView(rvLotList, this);
        mLotBindAdapter = new LotBindAdapter(null);
        mLotBindAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mLotBindAdapter.isFirstOnly(true);
        rvLotList.setAdapter(mLotBindAdapter);

        // 初始化已绑定载具列表
        rvAlreadyBindCarrierList = findViewById(R.id.rvAlreadyBindCarrierList);
        initRecyclerView(rvAlreadyBindCarrierList, this);
        lotAlreadyBindAdapter = new LotCarrierVerifyAdapter(null);
        lotAlreadyBindAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        lotAlreadyBindAdapter.isFirstOnly(true);
        lotAlreadyBindAdapter.setOnItemClickListener(null);
        rvAlreadyBindCarrierList.setAdapter(lotAlreadyBindAdapter);

        // 初始化设备号输入框
        etEquipmentId = findViewById(R.id.etEquipmentId);

        // 初始化扫描料盒号进行验证框
        etVerifyBingLotID = findViewById(R.id.etVerifyBingLotID);

        // 初始化载具类别下拉框
        flCarrierType = findViewById(R.id.flCarrierType);
        tvCarrierType = findViewById(R.id.tvCarrierType);
        ivCarrierType = findViewById(R.id.ivCarrierType);
        // 载具类别下拉框设定初始值：料盒
        tvCarrierType.setText(carrierBindTypeList.get(0));
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit, R.id.flCarrierType})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tvBaseSubmit) {

            if (StringUtils.isEmpty(getText(etLotID))) {
                showToast("批次号不能为空", false);
                return;
            }

            if (mLotBindAdapter.getData().size() <= 0) {
                showToast("载具不能为空", false);
                return;
            }

            if (StringUtils.isEmpty(getText(etEquipmentId))) {
                showToast("设备号不能为空", false);
                return;
            }

            FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                    (new TypeToken<BaseResponseBean<JSONObject>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(LotBindActivity.this, false, getSupportFragmentManager())) {
                        showToast("载具绑定批次成功", true);
                        finish();
                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<JSONObject>> response) {
                    super.onError(response);
                    loadError(response.getException(), "LOTREASSIGNMULTICARRIER");
                }
            };
            JsonObject map = new JsonObject();
            map.addProperty("ACTIONTYPE", "Bind");
            map.addProperty("LOTID", getText(etLotID));
            map.addProperty("EQUIPMENTID", getText(etEquipmentId));
            map.addProperty("CARRIERTYPE", String.valueOf(tvCarrierType.getText()));
            List<String> lotList = new ArrayList<>(mLotBindAdapter.getData());
            map.add("DURABLEIDLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());//传载具集合
            NetUtils.requestPostNet("IF.LOTVEHICLEBINDING", "Common", LotBindActivity.this, map, callBack);
        } else if (view.getId() == R.id.flCarrierType) {
            // 料盒类别下拉选择框选择
            carrierTypePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flCarrierType.getWidth(), carrierBindTypeList, ivCarrierType, (codeS, i) -> {
                tvCarrierType.setText(codeS);
                // 触发一次查询载具逻辑
                getLotBindCarrier();
            });
            FreeApi_PopUtils.setArrowShow(ivCarrierType);
            carrierTypePop.showAsDropDown(flCarrierType, 0, 0);
        }
    }

    // 获取批次绑定的载具
    private void getLotBindCarrier() {

        if (StringUtils.isAnyEmpty(getText(etLotID), getText(etEquipmentId), tvCarrierType.getText())) {
            return;
        }
        //获取批次绑定的料盒信息
        FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager(), false)) {
                    // 获取服务器传过来料盒数据
                    LotInfoEntity.LotBean lot = response.body().getResponse().getBody().getLOT();
                    List<String> lotCarrierList = response.body().getResponse().getBody().getDURABLELIST();
                    if (lotCarrierList != null && lotCarrierList.size() > 0) {
                        new Handler().post(() -> {
                            // 更新视图
                            // 这里直接使用addData会报错，参考代码后先获取视图的数据列表，修改数据列表的值
                            lotAlreadyBindAdapter.getData().clear();
                            lotAlreadyBindAdapter.getData().addAll(lotCarrierList);
                            lotAlreadyBindAdapter.notifyItemRangeChanged(0, lotCarrierList.size());
                        });
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "LOTQUERY");
                // 遇到错误直接清除错误
                // 已绑定的料盒列表
                MyUtils.clearDataInAdapter(lotAlreadyBindAdapter);
            }
        };

        // 请求前先清除下原有的数据
        MyUtils.clearDataInAdapter(lotAlreadyBindAdapter);
        // 清空掉搜索记录
        lotAlreadyBindAdapter.setSearchQuery(null);

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "query");
        map.addProperty("LOTID", getText(etLotID));
        map.addProperty("EQUIPMENTID", getText(etEquipmentId));
        map.addProperty("CARRIERTYPE", String.valueOf(tvCarrierType.getText()));
        NetUtils.requestPostNet("IF.LOTVEHICLEBINDING", "Common", LotBindActivity.this, map, callBack);
    }
}
